from django.shortcuts import render
from rest_framework import viewsets, permissions, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from django_filters import CharFilter
from django.shortcuts import get_object_or_404
from django.db import models
from .models import Server, Comment, Reply
from .serializers import (
    ServerSerializer, ServerDetailSerializer, CommentSerializer,
    ReplySerializer
)
from .filters import ServerFilter


class IsOwnerOrReadOnly(permissions.BasePermission):
    """自定义权限，仅允许对象的所有者编辑它"""
    
    def has_object_permission(self, request, view, obj):
        # 读取权限允许任何请求
        if request.method in permissions.SAFE_METHODS:
            return True
            
        # 写入权限仅限对象的所有者
        return obj.user == request.user


class ServerViewSet(viewsets.ModelViewSet):
    """MCP Server 视图集"""
    queryset = Server.objects.all()
    serializer_class = ServerSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = ServerFilter
    search_fields = ['name', 'name_cn', 'provider', 'description', 'description_cn']
    ordering_fields = ['name', 'created_at', 'updated_at']
    lookup_field = 'id'
    
    def get_permissions(self):
        """根据不同操作设置不同权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [permissions.IsAuthenticated()]
        return [permissions.AllowAny()]
    
    def get_serializer_class(self):
        """根据不同操作返回不同的序列化器"""
        if self.action == 'retrieve':
            return ServerDetailSerializer
        return ServerSerializer
    
    def get_queryset(self):
        """根据查询参数过滤 Server 列表"""
        queryset = super().get_queryset()
        
        # 默认不显示已删除的Server
        include_deleted = self.request.query_params.get('include_deleted', 'false').lower()
        if include_deleted != 'true':
            queryset = queryset.filter(is_deleted=False)
        
        # 过滤内部/外部 Server 
        is_internal = self.request.query_params.get('is_internal')
        if is_internal is not None:
            is_internal_bool = is_internal.lower() == 'true'
            queryset = queryset.filter(is_internal=is_internal_bool)

        # 过滤官方/非官方 Server
        is_official = self.request.query_params.get('is_official')
        if is_official is not None:
            is_official_bool = is_official.lower() == 'true'
            queryset = queryset.filter(is_official=is_official_bool)
            
        # 过滤访问模式
        access_mode = self.request.query_params.get('access_mode')
        if access_mode is not None:
            # 使用自定义过滤器处理
            queryset = self.filterset_class().filter_access_mode(queryset, 'access_mode', access_mode)
        
        return queryset
    
    @action(detail=True, methods=['get'])
    def readme(self, request, id=None):
        """获取 Server README内容"""
        server = self.get_object()
        language = request.query_params.get('language', 'en')
        
        if language.lower() == 'cn' and server.readme_cn:
            return Response({'content': server.readme_cn})
        elif server.readme:
            return Response({'content': server.readme})
        return Response({'content': ''})
    
    # @action(detail=False, methods=['get'])
    # def internal(self, request):
    #     """获取内部 Server 列表"""
    #     queryset = self.get_queryset().filter(is_internal=True)
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return self.get_paginated_response(serializer.data)
    #     serializer = self.get_serializer(queryset, many=True)
    #     return Response(serializer.data)
    
    # @action(detail=True, methods=['post'])
    # def status(self, request, id=None):
    #     """设置Server的删除状态"""
    #     server = self.get_object()
    #     is_deleted = request.data.get('is_deleted', False)
        
    #     if not isinstance(is_deleted, bool):
    #         return Response(
    #             {'error': 'is_deleted字段必须是布尔值'}, 
    #             status=status.HTTP_400_BAD_REQUEST
    #         )
        
    #     server.is_deleted = is_deleted
    #     server.save()
        
    #     return Response({
    #         'message': f'Server {server.name} 已{"删除" if is_deleted else "恢复"}',
    #         'is_deleted': is_deleted
    #     })


class CommentViewSet(viewsets.ModelViewSet):
    """评论视图集"""
    serializer_class = CommentSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    
    def get_queryset(self):
        server_id = self.kwargs.get('server_id')
        return Comment.objects.filter(server_id=server_id)
    
    def perform_create(self, serializer):
        server_id = self.kwargs.get('server_id')
        server = get_object_or_404(Server, id=server_id)
        serializer.save(user=self.request.user, server=server)


class ReplyViewSet(viewsets.ModelViewSet):
    """回复视图集"""
    serializer_class = ReplySerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    
    def get_queryset(self):
        comment_id = self.kwargs.get('comment_id')
        return Reply.objects.filter(comment_id=comment_id)
    
    def perform_create(self, serializer):
        comment_id = self.kwargs.get('comment_id')
        comment = get_object_or_404(Comment, id=comment_id)
        serializer.save(user=self.request.user, comment=comment)
